{% extends 'base/base.html' %}
{% load static %}

{% block Title %}
首页
{% endblock %}

{% block css %}
<link rel="stylesheet" href="{% static 'css/music-player-styles.css' %}">
{% endblock %}

{% block main %}
<div class="music-player-container">
    <div class="music-player-card">
        <!-- 播放器标题 -->
        <div class="player-title">
            <h1>🎵 音乐播放器</h1>
            <p>享受美妙的音乐时光</p>
        </div>

        <!-- 播放器布局 -->
        <div class="player-layout">
            <!-- 左侧音乐列表区域 - 25%宽度 -->
            <div class="music-list-section">
                <div class="music-list-title">音乐列表</div>
                <table id="musicTable">
                    <tbody>
                        {% for song in songs %}
                        <tr>
                            <td class="song-name" data-id="{{ song.id }}">{{ song.Title }}</td>
                            <td>{{ song.author }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
                
                <!-- 分页 -->
                <div class="pagination">
                    <a href="#" id="prevPage">上一页</a>
                    <span id="currentPage">1</span>
                    <a href="#" id="nextPage">下一页</a>
                </div>
            </div>

            <!-- 右侧播放器区域 -->
            <div class="player-main-section">
                <!-- 3D封面展示区域 -->
                <div class="cover-section">
                    <div class="ring-wrapper">
                        <div class="mini-ring">
                            <img class="coverBox" src="/media/head/1.jpg" alt="专辑封面">
                        </div>
                    </div>
                </div>

                <!-- 当前播放信息 -->
                <div class="current-song-info">
                    <h3 id="currentSong">选择一首歌曲开始播放</h3>
                    <p id="currentArtist">艺术家</p>
                </div>

                <!-- 进度条 -->
                <div class="progress-section">
                    <div class="progress-label">
                        <span id="currentTime">0:00</span>
                        <span id="totalTime">0:00</span>
                    </div>
                    <input type="range" id="progressBar" min="0" max="100" value="0">
                </div>

                <!-- 控制按钮 -->
                <div class="control-buttons">
                    <button class="control-btn" id="upp" title="上一首">
                        <span class="glyphicon glyphicon-backward"></span>
                    </button>
                    <button class="control-btn" id="ctrlBtn" title="播放/暂停">
                        <img src="/static/tu/bf.png" alt="播放">
                    </button>
                    <button class="control-btn" id="down" title="下一首">
                        <span class="glyphicon glyphicon-forward"></span>
                    </button>
                </div>

                <!-- 收藏按钮 - 完全恢复原来的结构 -->
                {% if user.is_authenticated %}
            <img class="love" src="{% static 'tu/收藏.png' %}"
     data-id="" data-islove="false">
    {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 音频播放器 -->
<audio id="player" preload="auto">
    <source src="" type="audio/mpeg">
</audio>
{% endblock %}

{% block js %}
{#    点击收藏#}
<script>
$('.love').on('click',function () {
    const id = $(this).attr('data-id');
    const islove = $(this).attr('data-islove')
    console.log('000000')
    console.log(id)
    console.log(islove, 1111)

    $.ajax({
        url:'/love/',
        type:'POST',
        data: {
            id: id ,
          islove:islove,
        csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val(),
        },
        dataType: 'json',

        success:function (res) {

            const loved = res.islove;
            console.log("ppppppppppp")
            console.log(loved)
             console.log("ppppppppppp")
            $('.love').attr('data-islove', loved);
            console.log(loved)
            $('.love').attr('src', loved ?
        '{% static "tu/收藏 (1).png" %}' :   // 实心（已收藏）
        '{% static "tu/收藏.png" %}');       // 空心（未收藏）


        }

    })


})
</script>

<script>
// 首页的分类按钮事件（保持原有功能）
$('.button').on('click', function () {
    const id = $(this).data('id');
    filterByClassify(id);
});
</script>

<script>
/* ================= 全局变量 ================= */
const audio = document.getElementById('player');
const btn   = document.getElementById('ctrlBtn');
const $ring = $('.mini-ring');

/* ================= 分页功能 ================= */
let currentPage = 1;
const songsPerPage = 10;

function resetPagination() {
    currentPage = 1;
    updatePagination();
}

function updatePagination() {
    const allRows = $('#musicTable tbody tr');
    const totalPages = Math.ceil(allRows.length / songsPerPage);
    
    // 显示当前页的歌曲
    allRows.hide();
    const startIndex = (currentPage - 1) * songsPerPage;
    const endIndex = startIndex + songsPerPage;
    allRows.slice(startIndex, endIndex).show();
    
    // 更新分页显示
    $('#currentPage').text(currentPage);
    $('#prevPage').toggle(currentPage > 1);
    $('#nextPage').toggle(currentPage < totalPages);
}

// 分页事件
$('#prevPage').on('click', function(e) {
    e.preventDefault();
    if (currentPage > 1) {
        currentPage--;
        updatePagination();
    }
});

$('#nextPage').on('click', function(e) {
    e.preventDefault();
    const allRows = $('#musicTable tbody tr');
    const totalPages = Math.ceil(allRows.length / songsPerPage);
    if (currentPage < totalPages) {
        currentPage++;
        updatePagination();
    }
});

/* ================= 分类筛选函数 ================= */
function filterByClassify(id) {
    $.ajax({
        url:'/classify/',
        type: 'GET',
        data: { id: id },
        dataType: 'json',
        success: function (res) {
            let html = '';
            if (res.musics && res.musics.length > 0) {
                for (var i = 0; i < res.musics.length; i++) {
                    var song = res.musics[i];
                    html += '<tr>';
                    html += '<td class="song-name" data-id="' + song.id + '">' + song.Title + '</td>';
                    html += '<td>' + song.author + '</td>';
                    html += '</tr>';
                }
            }
            else {
                html = '<tr><td colspan="2">暂无音乐</td></tr>';
            }
            $('#musicTable tbody').html(html);
            // 重置分页
            resetPagination();
            
            // 更新页面标题
            $('.music-list-title').text('分类音乐');
        },
        error: function () {
            alert('加载失败');
        }
    });
}

/* ================= 公用切歌函数 ================= */
function jumpTo(id) {
    if (!id) return;
    $.ajax({
        url: '/api/cover/',
        type: 'GET',
        data: { id: id },
        dataType: 'json',
        success: function (res) {
         $('.love').attr('data-id', res.id);
         $('.love').attr('data-islove', res.is_love);

         if(res.is_love){
             $('.love').attr('src','/static/tu/收藏 (1).png')
         }
         else {
              $('.love').attr('src','/static/tu/收藏.png')
         }

            if (!res.audio) { alert('暂无音频'); return; }

            /* 换歌 */
            audio.src = res.audio;
            audio.dataset.curId  = id;
            audio.dataset.nextId = res.next_id;
            audio.play();
            btn.src = '/static/tu/zt.png';

            /* 更新当前播放信息 */
            $('#currentSong').text(res.title || '未知歌曲');
            $('#currentArtist').text(res.artist || '未知艺术家');

            /* 换封面 + 圆环 */
            if (!res.cover) return;
            const covers = Array(4).fill(res.cover);
            $ring.empty();
            let html = '';
            covers.forEach(() => html += `<img class="coverBox" src="${res.cover}">`);
            $ring.append(html).addClass('spin');
            const R = 180;
            $ring.find('img').each((i, img) => {
                img.style.transform =
                    `translate(-50%,-50%) rotateY(${i * 90}deg) translateZ(${R}px)`;
            });

            /* 更新音乐列表选中状态 */
            $('#musicTable tbody tr').removeClass('playing');
            $(`#musicTable .song-name[data-id="${id}"]`).closest('tr').addClass('playing');
        },
        error: () => alert('加载失败')
    });
}

/* ================= 事件绑定 ================= */
$(function () {
    /* 初始化分页 */
    updatePagination();
    
    /* 处理URL参数中的分类筛选 */
    const urlParams = new URLSearchParams(window.location.search);
    const classifyId = urlParams.get('classify');
    if (classifyId) {
        // 如果有分类参数，自动筛选该分类
        filterByClassify(classifyId);
    }
    
    /* 1. 点歌名 */
    $('#musicTable').on('click', '.song-name', function () {
        const id = $(this).data('id');
        jumpTo(id);
    });

    /* 2. 上一首 */
    $('#upp').on('click', function () {
        const curId = parseInt(audio.dataset.curId || 0);
        const allRows = $('#musicTable tbody tr');
        const maxId = allRows.length;
        const prevId = curId <= 1 ? maxId : curId - 1;
        jumpTo(prevId);
    });

    /* 3. 下一首 */
    $('#down').on('click', function () {
        const curId = parseInt(audio.dataset.curId || 0);
        const allRows = $('#musicTable tbody tr');
        const maxId = allRows.length;
        const nextId = curId >= maxId ? 1 : curId + 1;
        jumpTo(nextId);
    });

    /* 4. 播放/暂停按钮 */
    $('#ctrlBtn').on('click', function () {
        if (audio.paused) {
            audio.play();
            $('#ctrlBtn img').attr('src', '/static/tu/zt.png');
            // 开始3D旋转
            $ring.addClass('spin');
        } else {
            audio.pause();
            $('#ctrlBtn img').attr('src', '/static/tu/bf.png');
            // 暂停3D旋转
            $ring.removeClass('spin');
        }
    });

    /* 5. 播放完自动下一首 */
    audio.addEventListener('ended', function () {
        const nextId = this.dataset.nextId;
        if (nextId) jumpTo(nextId);
        else {
            // 如果没有下一首，停止旋转
            $ring.removeClass('spin');
            $('#ctrlBtn img').attr('src', '/static/tu/bf.png');
        }
    });

    /* 6. 进度条 */
    const bar = document.getElementById('progressBar');
    audio.addEventListener('loadedmetadata', () => {
        bar.max = audio.duration;
        $('#totalTime').text(formatTime(audio.duration));
    });
    
    audio.addEventListener('timeupdate', () => {
        bar.value = audio.currentTime;
        $('#currentTime').text(formatTime(audio.currentTime));
    });
    
    bar.addEventListener('input', () => audio.currentTime = bar.value);

    /* 时间格式化函数 */
    function formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    }
});
</script>
{% endblock %}